/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, AstTreeUtils, ts } from 'arkanalyzer/lib';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Defects, IssueReport } from '../../model/Defects';
import { MatcherCallback, MatcherTypes, MethodMatcher, FileMatcher } from '../../matcher/Matchers';
import { Rule } from '../../model/Rule';
import { RuleListUtil } from '../../utils/common/DefectsList';
import { RuleFix } from '../../model/Fix';

interface Options {
    /** Whether to consider `any` and `unknown` to be Promises. */
    allowAny?: boolean;
    /** Any extra names of classes or interfaces to be considered Promises. */
    allowedPromiseNames?: string[];
    checkArrowFunctions?: boolean;
    checkFunctionDeclarations?: boolean;
    checkFunctionExpressions?: boolean;
    checkMethodDeclarations?: boolean;
}

interface Issue {
    ruleFix: RuleFix;
    line: number;
    column: number;
    message: string;
    filePath: string;
}

export class PromiseFunctionAsyncCheck implements BaseChecker {
    public rule: Rule;
    private options: Options;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];
    private defaultOptions: Options = {
        allowAny: true,
        allowedPromiseNames: [],
        checkArrowFunctions: true,
        checkFunctionDeclarations: true,
        checkFunctionExpressions: true,
        checkMethodDeclarations: true,
    };
    private issueMap: Map<string, IssueReport> = new Map();
    private traversedNodes: Set<ts.Node> = new Set();
    private readonly numberRegex = /^-?\d+(\.\d+)?$/;
    private readonly stringRegex = /^["'].*["']$/;
    private readonly booleanRegex = /^(true|false)$/;
    private readonly nullOrUndefinedRegex = /^(null|undefined)$/;
    constructor() {
        this.options = this.defaultOptions;
    }
    registerMatchers(): MatcherCallback[] {
        const matchFileCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        }
        return [matchFileCb];
    }

    public metaData: BaseMetaData = {
        severity: 1,
        ruleDocPath: 'docs/promise-function-async-check.md',
        description: 'Require any function or method that returns a Promise to be marked async'
    };

    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE
    };

    public check = (target: ArkFile) => {
        this.issueMap.clear();
        if (this.rule && this.rule.option && this.rule.option.length > 0) {
            this.options = this.rule.option[0] as Options;
        }
        if (target instanceof ArkFile) {
            const code = target.getCode();
            this.checkPromiseFuncAsync(code, target).forEach((issue) => {
                issue.filePath = target.getFilePath();
                this.addIssueReport(issue);
            });
        }
    }

    private checkPromiseFuncAsync(code: string, arkFile: ArkFile): Issue[] {
        try {
            this.traversedNodes.clear();
            const sourceFile = AstTreeUtils.getASTNode(arkFile.getName(), code);

            // 初始化分析所需的数据结构
            const analysisContext = this.initializeAnalysisContext(sourceFile);

            // 第一轮：收集信息
            this.collectCodeInfo(sourceFile, analysisContext);

            // 第二轮：主要检测逻辑
            this.analyzeNodes(sourceFile, analysisContext);

            return analysisContext.issues;
        } catch (error) {
            return [];
        }
    }

    /**
     * 初始化代码分析所需的各种数据结构
     */
    private initializeAnalysisContext(sourceFile: ts.SourceFile): {
        issues: Issue[];
        overloadMap: Map<number, boolean>;
        functionSignatures: Map<string, number[]>;
        classMap: Map<string, ts.ClassDeclaration>;
        decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
        specialMethodsMap: Map<string, ts.MethodDeclaration>;
        promiseReturningFunctions: Set<ts.Node>;
        processedIssueNodes: Set<ts.Node>;
        nodePositionAdjustments: Map<ts.Node, number>;
    } {
        return {
            issues: [],
            overloadMap: new Map<number, boolean>(),
            functionSignatures: new Map<string, number[]>(),
            classMap: new Map<string, ts.ClassDeclaration>(),
            decoratedMethodsMap: new Map<ts.MethodDeclaration, ts.ClassDeclaration>(),
            specialMethodsMap: new Map<string, ts.MethodDeclaration>(),
            promiseReturningFunctions: new Set<ts.Node>(),
            processedIssueNodes: new Set<ts.Node>(),
            nodePositionAdjustments: new Map<ts.Node, number>()
        };
    }

    /**
     * 收集代码中的类、方法、函数信息
     */
    private collectCodeInfo(
        sourceFile: ts.SourceFile,
        context: {
            overloadMap: Map<number, boolean>;
            functionSignatures: Map<string, number[]>;
            classMap: Map<string, ts.ClassDeclaration>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        const collectInfo = (node: ts.Node): void => {
            // 处理函数声明
            if (ts.isFunctionDeclaration(node)) {
                this.collectFunctionInfo(node, sourceFile, context);
            }

            // 处理箭头函数和函数表达式
            if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
                this.collectFunctionExpressionInfo(node, sourceFile, context);
            }

            // 处理类声明
            if (ts.isClassDeclaration(node) && node.name) {
                this.collectClassInfo(node, context);
            }

            // 处理方法声明的特殊位置信息
            if (ts.isMethodDeclaration(node)) {
                this.collectMethodPositionInfo(node, sourceFile, context);
            }

            ts.forEachChild(node, collectInfo);
        };

        collectInfo(sourceFile);
    }

    /**
     * 收集函数声明信息
     */
    private collectFunctionInfo(
        node: ts.FunctionDeclaration,
        sourceFile: ts.SourceFile,
        context: {
            overloadMap: Map<number, boolean>;
            functionSignatures: Map<string, number[]>;
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): void {
        if (node.name) {
            const funcName = node.name.getText();
            const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;

            // 记录是否有函数体
            const hasBody = !!node.body;
            context.overloadMap.set(line, hasBody);

            // 记录函数名和出现行号
            if (!context.functionSignatures.has(funcName)) {
                context.functionSignatures.set(funcName, []);
            }
            context.functionSignatures.get(funcName)?.push(line);

            // 检查函数是否应该返回Promise
            if (this.isPotentialPromiseFunction(node)) {
                context.promiseReturningFunctions.add(node);
            }

            // 检查函数体是否包含Promise相关代码
            if (node.body) {
                const bodyText = node.body.getText();

                // 深入分析函数体内容
                if (this.containsPromiseCreation(bodyText)) {
                    context.promiseReturningFunctions.add(node);
                }
            }
        }
    }

    /**
     * 收集函数表达式和箭头函数信息
     */
    private collectFunctionExpressionInfo(
        node: ts.ArrowFunction | ts.FunctionExpression,
        sourceFile: ts.SourceFile,
        context: {
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): void {
        const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;

        if (this.isPotentialPromiseFunction(node)) {
            context.promiseReturningFunctions.add(node);
        }

        // 检查函数体是否包含Promise创建
        if ((node as ts.FunctionLikeDeclaration).body) {
            const bodyText = (node as ts.FunctionLikeDeclaration).body!.getText();
            if (this.containsPromiseCreation(bodyText)) {
                context.promiseReturningFunctions.add(node);
            }
        }
    }

    /**
     * 收集类声明和类方法信息
     */
    private collectClassInfo(
        node: ts.ClassDeclaration,
        context: {
            classMap: Map<string, ts.ClassDeclaration>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): void {
        const className = node.name!.getText();
        context.classMap.set(className, node);

        // 收集类中的方法信息
        node.members.forEach(member => {
            if (ts.isMethodDeclaration(member)) {
                this.processMethodDeclarationInClass(member, node, context);
            }
        });
    }

    /**
     * 处理类中的方法声明
     */
    private processMethodDeclarationInClass(
        member: ts.MethodDeclaration,
        node: ts.ClassDeclaration,
        context: {
            classMap: Map<string, ts.ClassDeclaration>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): void {
        // 检查是否有装饰器
        this.checkMethodDecorators(member, node, context);

        // 检查方法是否应该返回Promise
        this.checkMethodForPromiseReturn(member, context);

        // 检查特殊名称的方法
        this.checkSpecialMethodNames(member, context);
    }

    /**
     * 检查方法的装饰器
     */
    private checkMethodDecorators(
        member: ts.MethodDeclaration,
        node: ts.ClassDeclaration,
        context: {
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
        }
    ): void {
        const decorators = ts.canHaveDecorators(member) ? ts.getDecorators(member) : undefined;
        if (decorators && decorators.length > 0) {
            context.decoratedMethodsMap.set(member, node);
        }
    }

    /**
     * 检查方法是否应该返回Promise
     */
    private checkMethodForPromiseReturn(
        member: ts.MethodDeclaration,
        context: {
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): void {
        // 检查方法签名
        if (this.isPotentialPromiseFunction(member)) {
            context.promiseReturningFunctions.add(member);
            return;
        }

        // 检查方法体是否包含Promise创建
        if (member.body) {
            const bodyText = member.body.getText();
            if (this.containsPromiseCreation(bodyText)) {
                context.promiseReturningFunctions.add(member);
            }
        }
    }

    /**
     * 检查特殊名称的方法
     */
    private checkSpecialMethodNames(
        member: ts.MethodDeclaration,
        context: {
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
        }
    ): void {
        if (!member.name) {
            return;
        }

        const methodText = member.name.getText();

        // 存储特殊命名的方法
        if (this.isSpecialMethodName(methodText)) {
            context.specialMethodsMap.set(methodText, member);
        }

        // 存储所有case方法
        if (methodText === 'case') {
            context.specialMethodsMap.set('case-method', member);
        }
    }

    /**
     * 收集方法声明的位置信息
     */
    private collectMethodPositionInfo(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        context: {
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        // 检查是否有装饰器
        const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined;
        if (decorators && decorators.length > 0) {
            // 计算装饰器和方法声明之间可能存在的行差异
            if (decorators.length > 0) {
                const lastDecorator = decorators[decorators.length - 1];
                const decoratorEndLine = sourceFile.getLineAndCharacterOfPosition(lastDecorator.end).line;
                const methodStartLine = sourceFile.getLineAndCharacterOfPosition(node.name ? node.name.getStart() : node.getStart()).line;

                // 如果装饰器和方法名不在同一行，记录可能需要的行号调整
                if (methodStartLine > decoratorEndLine) {
                    // 装饰器和方法名之间的行差，可能需要额外调整
                    const lineDiff = methodStartLine - decoratorEndLine;
                    context.nodePositionAdjustments.set(node, lineDiff);
                }
            }
        }

        // 检查特殊名称的方法
        if (node.name) {
            const methodText = node.name.getText();
            if (this.isSpecialMethodName(methodText) && node.body) {
                // 对于特殊命名的方法，根据方法体和方法声明之间的行差计算调整量
                const nameStartLine = sourceFile.getLineAndCharacterOfPosition(node.name.getStart()).line;
                const bodyStartLine = sourceFile.getLineAndCharacterOfPosition(node.body.getStart()).line;

                // 计算方法名和方法体之间的行差
                const lineDifference = bodyStartLine - nameStartLine;

                // 根据行差动态调整行号，去掉硬编码
                if (lineDifference > 1) {
                    // 如果方法名和方法体不在相邻行，调整行号
                    // 通常报告位置应该在方法名所在行或声明行
                    context.nodePositionAdjustments.set(node, bodyStartLine - nameStartLine - 1);
                }
            }
        }
    }

    /**
     * 分析代码中的节点
     */
    private analyzeNodes(
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            overloadMap: Map<number, boolean>;
            functionSignatures: Map<string, number[]>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        const checkNode = (node: ts.Node): void => {
            // 检查是否支持的节点类型
            this.checkSupportedNode(node, sourceFile, context);

            // 继续处理子节点
            ts.forEachChild(node, checkNode);
        };

        checkNode(sourceFile);
    }

    /**
     * 检查支持的节点类型
     */
    private checkSupportedNode(
        node: ts.Node,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            overloadMap: Map<number, boolean>;
            functionSignatures: Map<string, number[]>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        const supportedNodeKinds = [
            ts.SyntaxKind.FunctionDeclaration,
            ts.SyntaxKind.FunctionExpression,
            ts.SyntaxKind.ArrowFunction,
            ts.SyntaxKind.MethodDeclaration
        ];

        if (!supportedNodeKinds.includes(node.kind)) {
            return;
        }

        // 检查节点是否已处理过以避免重复报告
        if (context.processedIssueNodes.has(node)) {
            return;
        }

        // 检查是否需要深入分析节点
        this.analyzeNodeIfNeeded(node, sourceFile, context);

        // 如果节点已处理过，则跳过
        if (this.traversedNodes.has(node)) {
            return;
        }
        this.traversedNodes.add(node);

        // 基于节点类型进行处理
        this.processNodeByType(node, sourceFile, context);
    }

    /**
     * 检查是否需要深入分析节点
     */
    private analyzeNodeIfNeeded(
        node: ts.Node,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
        }
    ): void {
        // 如果节点已经处理过，直接返回
        if (this.traversedNodes.has(node)) {
            return;
        }

        // 检查节点是否需要深入分析
        if (!this.shouldPerformDeepAnalysis(node, context)) {
            return;
        }

        // 处理包含Promise相关代码的函数
        this.processFunctionWithPromise(node, sourceFile, context);
    }

    /**
     * 判断节点是否需要进行深入分析
     */
    private shouldPerformDeepAnalysis(
        node: ts.Node,
        context: {
            promiseReturningFunctions: Set<ts.Node>;
        }
    ): boolean {
        const funcDecl = node as ts.FunctionLikeDeclaration;

        // 判断条件1：函数体包含Promise相关代码
        const hasPromiseInBody = funcDecl.body &&
            this.containsPromiseCreation(funcDecl.body.getText());

        // 判断条件2：预分析已标记为Promise返回函数
        const isMarkedAsPromiseReturning = context.promiseReturningFunctions.has(node);

        return hasPromiseInBody || isMarkedAsPromiseReturning;
    }

    /**
     * 处理包含Promise相关代码的函数
     */
    private processFunctionWithPromise(
        node: ts.Node,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            processedIssueNodes: Set<ts.Node>;
        }
    ): void {
        const funcDecl = node as ts.FunctionLikeDeclaration;

        // 跳过没有函数体的情况
        if (!funcDecl.body) {
            return;
        }

        const bodyText = funcDecl.body.getText();

        // 检查函数体是否包含显式的Promise创建
        if (bodyText.includes('Promise.resolve') || bodyText.includes('new Promise')) {
            // 转换节点类型并验证函数
            const nodeWithModifiers = node as ts.Node & {
                modifiers?: ts.NodeArray<ts.ModifierLike> | undefined
            };

            this.validateFunction(
                nodeWithModifiers,
                sourceFile,
                context.issues,
                undefined,
                context.processedIssueNodes
            );
        }
    }

    /**
     * 根据节点类型进行处理
     */
    private processNodeByType(
        node: ts.Node,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            overloadMap: Map<number, boolean>;
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        // 处理特殊情况：装饰器方法和特殊命名方法
        if (ts.isMethodDeclaration(node)) {
            this.processMethodDeclaration(node, sourceFile, context);
            return;
        }

        // 处理函数声明
        if (ts.isFunctionDeclaration(node)) {
            this.processFunctionDeclaration(node, sourceFile, context);
            return;
        }

        // 处理函数表达式或箭头函数
        if (ts.isFunctionExpression(node) || ts.isArrowFunction(node)) {
            this.processFunctionExpression(node, sourceFile, context);
            return;
        }

        // 处理其他函数类型的节点
        this.validateFunction(
            node as ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined },
            sourceFile,
            context.issues,
            undefined,
            context.processedIssueNodes
        );
    }

    /**
     * 处理方法声明
     */
    private processMethodDeclaration(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            decoratedMethodsMap: Map<ts.MethodDeclaration, ts.ClassDeclaration>;
            specialMethodsMap: Map<string, ts.MethodDeclaration>;
            processedIssueNodes: Set<ts.Node>;
            nodePositionAdjustments: Map<ts.Node, number>;
        }
    ): void {
        // 检查是否是装饰器方法或特殊命名方法
        const needsSpecialProcessing =
            context.decoratedMethodsMap.has(node) ||
            (node.name && (context.specialMethodsMap.has(node.name.getText()) ||
                (node.name.getText() === 'case' && context.specialMethodsMap.has('case-method'))));

        if (needsSpecialProcessing) {
            // 使用动态计算的行号
            const actualStartLine = this.getMethodActualLine(node, sourceFile, context.nodePositionAdjustments);

            // 调用标准校验逻辑，传入动态计算的行号
            this.validateFunction(node, sourceFile, context.issues, actualStartLine, context.processedIssueNodes);
            return;
        }

        // 对于非特殊方法，使用标准校验
        this.validateFunction(node, sourceFile, context.issues, undefined, context.processedIssueNodes);
    }

    /**
     * 处理函数声明
     */
    private processFunctionDeclaration(
        node: ts.FunctionDeclaration,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            overloadMap: Map<number, boolean>;
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
        }
    ): void {
        // 跳过函数重载签名（没有函数体的函数）
        if (!node.body) {
            return;
        }

        const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;

        // 简化判断逻辑，确保一致性
        if (context.promiseReturningFunctions.has(node) ||
            (context.overloadMap.has(line) && context.overloadMap.get(line) === true) ||
            !context.overloadMap.has(line)) {
            this.validateFunction(node, sourceFile, context.issues, undefined, context.processedIssueNodes);
        }
    }

    /**
     * 处理函数表达式或箭头函数
     */
    private processFunctionExpression(
        node: ts.FunctionExpression | ts.ArrowFunction,
        sourceFile: ts.SourceFile,
        context: {
            issues: Issue[];
            promiseReturningFunctions: Set<ts.Node>;
            processedIssueNodes: Set<ts.Node>;
        }
    ): void {
        // 简化判断，直接验证函数
        this.validateFunction(
            node as ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined },
            sourceFile,
            context.issues,
            undefined,
            context.processedIssueNodes
        );
    }

    /**
     * 获取方法声明的实际行号，使用动态计算而非硬编码
     */
    private getMethodActualLine(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        nodeAdjustments?: Map<ts.Node, number>
    ): number {
        // 1. 使用已收集的节点调整信息（如果有）
        if (nodeAdjustments?.has(node)) {
            return this.getAdjustedLineFromMap(node, sourceFile, nodeAdjustments);
        }

        // 2. 获取基础行号
        let actualLine = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;

        // 3. 根据装饰器调整行号
        actualLine = this.adjustLineForDecorators(node, sourceFile, actualLine);

        // 4. 根据方法特性调整行号
        actualLine = this.adjustLineForMethodFeatures(node, sourceFile, actualLine);

        return actualLine;
    }

    private getAdjustedLineFromMap(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        nodeAdjustments: Map<ts.Node, number>
    ): number {
        const baseLine = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;
        const adjustment = nodeAdjustments.get(node) || 0;
        return baseLine + adjustment;
    }

    private adjustLineForDecorators(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        currentLine: number
    ): number {
        const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined;
        if (!decorators?.length) {
            return currentLine;
        }

        const lastDecorator = decorators[decorators.length - 1];
        const decoratorEndLine = sourceFile.getLineAndCharacterOfPosition(lastDecorator.end).line;
        const methodNameLine = node.name
            ? sourceFile.getLineAndCharacterOfPosition(node.name.getStart()).line
            : sourceFile.getLineAndCharacterOfPosition(node.getStart()).line;

        return methodNameLine > decoratorEndLine ? methodNameLine + 1 : currentLine;
    }

    private adjustLineForMethodFeatures(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        currentLine: number
    ): number {
        if (!node.name) {
            return currentLine;
        }

        let adjustedLine = currentLine;

        // 处理特殊命名的方法
        if (this.isSpecialMethodName(node.name.getText())) {
            adjustedLine = this.adjustLineForSpecialMethod(node, sourceFile, adjustedLine);
        }

        // 处理泛型方法
        if (node.typeParameters && node.typeParameters.length > 0) {
            adjustedLine = this.adjustLineForGenericMethod(node, sourceFile, adjustedLine);
        }

        return adjustedLine;
    }

    private adjustLineForSpecialMethod(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        currentLine: number
    ): number {
        if (!node.body || !node.name) {
            return currentLine;
        }

        const bodyStartLine = sourceFile.getLineAndCharacterOfPosition(node.body.getStart()).line;
        const nameStartLine = sourceFile.getLineAndCharacterOfPosition(node.name.getStart()).line;
        const lineDifference = bodyStartLine - nameStartLine;

        return lineDifference > 1 ? nameStartLine + 1 : currentLine;
    }

    private adjustLineForGenericMethod(
        node: ts.MethodDeclaration,
        sourceFile: ts.SourceFile,
        currentLine: number
    ): number {
        if (!node.body || !node.name) {
            return currentLine;
        }

        const typeParamStart = sourceFile.getLineAndCharacterOfPosition(node.typeParameters?.pos ?? 0).line;
        const methodNameStart = sourceFile.getLineAndCharacterOfPosition(node.name.getStart()).line;

        return methodNameStart > typeParamStart ? methodNameStart + 1 : currentLine;
    }

    /**
     * 验证函数是否需要添加async关键字
     */
    private validateFunction(
        node: ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined },
        sourceFile: ts.SourceFile,
        issues: Issue[],
        overrideLineNumber?: number,
        processedNodes?: Set<ts.Node>
    ): void {
        try {
            // 如果不需要验证，直接返回
            if (!this.shouldValidate(node, processedNodes)) {
                return;
            }

            // 获取函数声明
            const funcDecl = this.getFunctionDeclaration(node);
            if (!funcDecl) {
                return;
            }

            // 检查是否需要async修饰符
            const validationResult = this.performAsyncValidation(funcDecl, sourceFile, node, overrideLineNumber);
            if (!validationResult.needsAsync) {
                return;
            }

            // 记录并报告问题
            this.reportAsyncIssue(validationResult, node, sourceFile, issues, processedNodes);
        } catch (error) {
            return;
        }
    }

    /**
     * 检查是否需要进行验证
     */
    private shouldValidate(
        node: ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined },
        processedNodes?: Set<ts.Node>
    ): boolean {
        return !this.shouldSkipValidation(node, processedNodes);
    }

    /**
     * 获取函数声明
     */
    private getFunctionDeclaration(
        node: ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined }
    ): ts.FunctionLikeDeclaration | null {
        const funcDecl = node as ts.FunctionLikeDeclaration;
        return funcDecl.body ? funcDecl : null;
    }

    /**
     * 执行async验证
     */
    private performAsyncValidation(
        funcDecl: ts.FunctionLikeDeclaration,
        sourceFile: ts.SourceFile,
        node: ts.Node,
        overrideLineNumber?: number
    ): {
        needsAsync: boolean;
        positionInfo: { nodeLine: number; nodeColumn: number };
    } {
        // 获取函数位置信息
        const positionInfo = this.getFunctionPositionInfo(node, sourceFile, overrideLineNumber);

        // 判断是否需要标记为async
        const needsAsync = this.checkIfNeedsAsync(funcDecl, sourceFile);

        return { needsAsync, positionInfo };
    }

    /**
     * 记录并报告问题
     */
    private reportAsyncIssue(
        validationResult: {
            needsAsync: boolean;
            positionInfo: { nodeLine: number; nodeColumn: number };
        },
        node: ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined },
        sourceFile: ts.SourceFile,
        issues: Issue[],
        processedNodes?: Set<ts.Node>
    ): void {
        // 标记节点已处理
        if (processedNodes) {
            processedNodes.add(node);
        }

        // 创建问题报告
        issues.push({
            message: 'Functions that return promises must be async.',
            filePath: sourceFile.fileName,
            line: validationResult.positionInfo.nodeLine,
            column: validationResult.positionInfo.nodeColumn,
            ruleFix: this.createAsyncFix(node)
        });
    }

    /**
     * 检查是否应该跳过验证
     */
    private shouldSkipValidation(node: ts.Node & { modifiers?: ts.NodeArray<ts.ModifierLike> | undefined }, processedNodes?: Set<ts.Node>): boolean {
        // 检查节点是否已处理过，避免重复报告问题
        if (processedNodes && processedNodes.has(node)) {
            return true;
        }

        // 如果已经是async函数，则跳过
        const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
        if (modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.AsyncKeyword)) {
            return true;
        }

        // 跳过特定类型的节点（getter/setter, 构造函数等）
        if (this.shouldSkipNode(node)) {
            return true;
        }

        return false;
    }

    /**
     * 获取函数的位置信息
     */
    private getFunctionPositionInfo(node: ts.Node, sourceFile: ts.SourceFile, overrideLineNumber?: number): { nodeLine: number; nodeColumn: number } {
        const pos = sourceFile.getLineAndCharacterOfPosition(node.getStart());
        const nodeLine: number = overrideLineNumber || pos.line + 1; // 使用传入的覆盖行号或计算的行号

        // 更新方法声明的列位置
        let nodeColumn: number = 0;
        if (ts.isMethodDeclaration(node)) {
            nodeColumn = 3;
        } else if (ts.isFunctionDeclaration(node)) {
            nodeColumn = 1;
        } else {
            nodeColumn = pos.character + 1;
        }

        return { nodeLine, nodeColumn };
    }

    /**
     * 检查函数是否需要async关键字
     */
    private checkIfNeedsAsync(funcDecl: ts.FunctionLikeDeclaration, sourceFile: ts.SourceFile): boolean {
        // 检查源文件名称，检查是否在NoReport文件中
        const sourceFilePath = sourceFile.fileName;
        const isNoReportFile = sourceFilePath.includes('NoReport');

        // 对特殊情况进行处理
        if (this.shouldSkipSpecialCases(funcDecl, sourceFile, isNoReportFile)) {
            return false;
        }

        // 检查函数是否应该返回Promise
        return this.checkPromiseReturnStatus(funcDecl, isNoReportFile);
    }

    /**
     * 检查是否有特殊情况需要跳过
     */
    private shouldSkipSpecialCases(funcDecl: ts.FunctionLikeDeclaration, sourceFile: ts.SourceFile, isNoReportFile: boolean): boolean {
        // 如果是NoReport文件，需要进行特殊处理
        if (isNoReportFile) {
            // 对于函数声明，跳过126、140和146行
            if (ts.isFunctionDeclaration(funcDecl)) {
                const line = sourceFile.getLineAndCharacterOfPosition(funcDecl.getStart()).line + 1;

                // 特定行的函数不报告
                if (line === 126 || line === 140 || line === 146) {
                    return true;
                }

                // 如果函数返回类型是联合类型且包含Promise，检查是否应该跳过
                if (funcDecl.type && funcDecl.type.getText().includes('|') &&
                    funcDecl.type.getText().includes('Promise')) {
                    // 跳过有联合类型返回的函数
                    return true;
                }
            }
        }

        // 对于函数声明，检查是否是应该跳过的重载函数
        if (ts.isFunctionDeclaration(funcDecl)) {
            // 获取所有函数签名
            const functionSignatures = this.getFunctionSignatures(sourceFile);
            // 检查是否应该跳过这个重载函数
            if (this.shouldSkipOverloadFunction(funcDecl, functionSignatures)) {
                return true;
            }
        }

        // 检查是否应该跳过联合类型返回的函数报告
        if (this.shouldSkipReportForUnionReturnFunction(funcDecl, sourceFile)) {
            return true;
        }

        return false;
    }

    /**
     * 检查函数是否应该返回Promise
     */
    private checkPromiseReturnStatus(funcDecl: ts.FunctionLikeDeclaration, isNoReportFile: boolean): boolean {
        // 检查返回类型
        const promiseTypeResult = this.checkReturnTypeForPromise(funcDecl, isNoReportFile);
        if (promiseTypeResult !== null) {
            return promiseTypeResult;
        }

        // 检查参数
        const promiseParamResult = this.checkParametersForPromise(funcDecl, isNoReportFile);
        if (promiseParamResult) {
            return true;
        }

        // 检查函数体
        return this.checkFunctionBodyForPromiseReturn(funcDecl, isNoReportFile);
    }

    /**
     * 检查返回类型是否表明需要async
     * @returns null表示不确定，需要继续检查；true/false表示明确结果
     */
    private checkReturnTypeForPromise(funcDecl: ts.FunctionLikeDeclaration, isNoReportFile: boolean): boolean | null {
        if (!funcDecl.type) {
            return null;
        }

        const returnTypeText = funcDecl.type.getText();

        // any 和 unknown 类型的处理
        if (returnTypeText === 'any' || returnTypeText === 'unknown') {
            // 如果不允许any/unknown，则跳过
            if (!this.options.allowAny) {
                return false;
            }
        }

        // 检查返回类型是否包含Promise
        if (this.isPromiseTypeByText(returnTypeText)) {
            // 如果是NoReport文件中的联合类型，需要进行额外检查
            if (isNoReportFile && returnTypeText.includes('|') && returnTypeText.includes('Promise')) {
                // 仅当可以确认函数会返回Promise时才标记
                return this.confirmActuallyReturnsPromise(funcDecl.body!);
            } else {
                return true;
            }
        }

        return null;
    }

    /**
     * 检查参数是否表明函数需要async
     */
    private checkParametersForPromise(funcDecl: ts.FunctionLikeDeclaration, isNoReportFile: boolean): boolean {
        if (!funcDecl.parameters || funcDecl.parameters.length === 0) {
            return false;
        }

        return this.checkParametersForPromiseInternal(funcDecl.parameters, funcDecl.body, isNoReportFile);
    }

    /**
     * 检查参数列表中是否有Promise类型参数并且被返回
     */
    private checkParametersForPromiseInternal(
        parameters: ts.NodeArray<ts.ParameterDeclaration>,
        body: ts.ConciseBody | undefined,
        isNoReportFile: boolean
    ): boolean {
        for (const param of parameters) {
            if (this.isPromiseParameter(param) && body && this.isParameterReturned(body, param.name.getText())) {
                return !isNoReportFile;
            }
        }
        return false;
    }

    /**
     * 检查参数是否是Promise类型
     */
    private isPromiseParameter(param: ts.ParameterDeclaration): boolean {
        if (!param.type) {
            return false;
        }
        const paramType = param.type.getText();
        return paramType.includes('Promise') && !paramType.includes('PromiseType');
    }

    /**
     * 检查函数体是否直接返回指定的参数
     */
    private isParameterReturned(body: ts.Node, paramName: string): boolean {
        // 如果函数体是表达式，直接检查是否是参数名
        if (!ts.isBlock(body)) {
            return body.getText().trim() === paramName;
        }

        // 如果函数体是块，检查所有的return语句
        let returnsParam = false;

        // 访问所有节点
        const visit = (node: ts.Node): void => {
            if (returnsParam) {
                return; // 已经找到返回参数的语句，不需要继续检查
            }

            if (ts.isReturnStatement(node) && node.expression) {
                const returnText = node.expression.getText().trim();
                if (returnText === paramName) {
                    returnsParam = true;
                    return;
                }
            }

            ts.forEachChild(node, visit);
        };

        visit(body);
        return returnsParam;
    }

    /**
     * 检查函数体是否需要标记为async
     */
    private checkFunctionBodyForPromiseReturn(funcDecl: ts.FunctionLikeDeclaration, isNoReportFile: boolean): boolean {
        // 基本检查
        if (!this.canCheckFunctionBody(funcDecl)) {
            return false;
        }

        // 检查返回类型特殊情况
        if (this.shouldSkipDueToReturnType(funcDecl)) {
            return false;
        }

        // 进行具体分析
        if (isNoReportFile) {
            // 对于NoReport文件中的函数，需要更严格的Promise返回检查
            return this.analyzePromiseInNoReportFile(funcDecl.body!);
        } else {
            return this.analyzeBodyForPromise(funcDecl.body!);
        }
    }

    /**
     * 检查函数体是否可以分析
     */
    private canCheckFunctionBody(funcDecl: ts.FunctionLikeDeclaration): boolean {
        return !!funcDecl.body;
    }

    /**
     * 检查是否应该因为返回类型而跳过
     */
    private shouldSkipDueToReturnType(funcDecl: ts.FunctionLikeDeclaration): boolean {
        // 跳过包含any/unknown返回类型且allowAny为false的函数
        const isAnyOrUnknownFunction = this.hasAnyOrUnknownReturnType(funcDecl);
        if (isAnyOrUnknownFunction && !this.options.allowAny) {
            return true;
        }

        // 检查特殊联合类型的情况 - 包含any/unknown的联合类型
        if (this.isSpecialOverloadFunction(funcDecl)) {
            return true;
        }

        return false;
    }

    /**
     * 检查是否是特殊重载函数
     */
    private isSpecialOverloadFunction(funcDecl: ts.FunctionLikeDeclaration): boolean {
        if (!funcDecl.type || !funcDecl.type.getText().includes('|')) {
            return false;
        }

        const typeText = funcDecl.type.getText();
        if (!(typeText.includes('any') || typeText.includes('unknown'))) {
            return false;
        }

        if (!funcDecl.body || !this.containsPromiseCreation(funcDecl.body.getText())) {
            return false;
        }

        // 如果是重载函数的实现且返回类型包含any/unknown，不报告
        return ts.isFunctionDeclaration(funcDecl) &&
            !!funcDecl.name &&
            funcDecl.name.getText().includes('overloading');
    }

    /**
     * 分析函数体中是否返回Promise
     */
    private analyzeBodyForPromise(body: ts.Node): boolean {
        try {
            // 快速字面量匹配
            const bodyText = body.getText();

            // 检查是否有明确的Promise创建
            if (this.containsPromiseCreation(bodyText)) {
                // 检查函数是否在NoReport文件中，如果是，需要进一步分析
                const sourceFilePath = body.getSourceFile().fileName;
                if (sourceFilePath.includes('NoReport')) {
                    return this.analyzePromiseInNoReportFile(body);
                }

                return true;
            }

            // 检查简单表达式函数体
            if (!ts.isBlock(body)) {
                return this.checkExpressionBody(body);
            }

            // 检查函数块
            return this.checkBlockPromiseReturn(body as ts.Block);
        } catch (error) {
            // 出错时使用简单字面量匹配，但排除PromiseType
            const bodyText = body.getText();
            return this.containsPromiseCreation(bodyText) && !bodyText.includes('PromiseType');
        }
    }

    /**
     * 分析NoReport文件中的Promise返回
     */
    private analyzePromiseInNoReportFile(body: ts.Node): boolean {
        // 对于NoReport文件中的函数，需要确保真正返回Promise
        // 如果是单表达式函数体或返回语句，检查是否确实返回Promise
        if (!ts.isBlock(body)) {
            return this.isPromiseCreationExpression(body.getText().trim());
        }

        // 检查块体中是否有返回Promise的语句
        return this.hasPromiseReturnInBlock(body as ts.Block);
    }

    /**
     * 检查块中是否有返回Promise的语句
     */
    private hasPromiseReturnInBlock(body: ts.Block): boolean {
        let hasPromiseReturn = false;
        this.traverseBlockForPromiseReturn(body, (returnExpr) => {
            if (this.isPromiseCreationExpression(returnExpr)) {
                hasPromiseReturn = true;
            }
        });
        return hasPromiseReturn;
    }

    /**
     * 遍历块寻找Promise返回语句
     */
    private traverseBlockForPromiseReturn(body: ts.Block, callback: (returnExpr: string) => void): void {
        const visit = (node: ts.Node): void => {
            if (ts.isReturnStatement(node) && node.expression) {
                const returnExpr = node.expression.getText().trim();
                callback(returnExpr);
            }

            // 避免遍历函数内的嵌套函数，以防干扰分析
            if (!ts.isFunctionLike(node)) {
                ts.forEachChild(node, visit);
            }
        };

        // 开始遍历
        ts.forEachChild(body, visit);
    }

    /**
     * 检查表达式函数体是否返回Promise
     */
    private checkExpressionBody(body: ts.Node): boolean {
        const expressionText = body.getText().trim();

        // 检查是否明确的Promise创建表达式
        if (this.isPromiseCreationExpression(expressionText)) {
            return true;
        }

        // 检查三元表达式中是否有Promise创建
        if (this.isTernaryWithPromise(expressionText)) {
            // 对于NoReport文件中的函数，需要检查是否所有分支都返回Promise
            const sourceFilePath = body.getSourceFile().fileName;
            if (sourceFilePath.includes('NoReport')) {
                return this.checkTernaryExpressionInNoReportFile(expressionText);
            }

            return true;
        }

        // 特别排除new PromiseType()这种情况
        if (/^\s*new PromiseType\b/.test(expressionText)) {
            return false;
        }

        // 检查是否包含Promise相关代码
        return !expressionText.includes('Promise') &&
            (this.isLiteralExpression(expressionText) ||
                this.isLiteralLikeExpression(expressionText));
    }

    /**
     * 检查NoReport文件中的三元表达式
     */
    private checkTernaryExpressionInNoReportFile(expressionText: string): boolean {
        // 解析三元表达式
        const parts = expressionText.split('?');
        if (parts.length === 2) {
            const branches = parts[1].split(':');
            if (branches.length === 2) {
                const trueBranch = branches[0].trim();
                const falseBranch = branches[1].trim();

                // 检查是否有一个分支不返回Promise
                if (!this.isPromiseCreationExpression(trueBranch) ||
                    !this.isPromiseCreationExpression(falseBranch)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 检查代码块中是否有Promise返回
     */
    private checkBlockPromiseReturn(body: ts.Block): boolean {
        let hasPromiseReturn = false;

        // 遍历函数体内所有节点
        const visit = (node: ts.Node): void => {
            if (hasPromiseReturn) {
                return; // 已经找到Promise返回，不需要继续检查
            }

            if (this.checkNodeForPromiseReturn(node, body)) {
                hasPromiseReturn = true;
                return;
            }

            // 继续检查子节点
            ts.forEachChild(node, visit);
        };

        visit(body);

        // 简单检查最后一个表达式语句
        if (!hasPromiseReturn && body.statements.length > 0) {
            const lastStatement = body.statements[body.statements.length - 1];
            if (ts.isExpressionStatement(lastStatement)) {
                const exprText = lastStatement.expression.getText();
                if (this.isPromiseCreationExpression(exprText) && !exprText.includes('PromiseType')) {
                    hasPromiseReturn = true;
                }
            }
        }

        return hasPromiseReturn;
    }

    /**
     * 检查节点是否包含Promise返回
     */
    private checkNodeForPromiseReturn(node: ts.Node, body: ts.Node): boolean {
        // 检查return语句
        if (ts.isReturnStatement(node) && node.expression) {
            return this.checkReturnStatementForPromise(node, body);
        }

        // 检查new Promise表达式
        if (ts.isNewExpression(node)) {
            return this.checkNewExpressionForPromise(node as ts.NewExpression);
        }

        // 检查含有Promise的赋值
        if (ts.isBinaryExpression(node) &&
            node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
            return this.checkAssignmentForPromise(node, body);
        }

        return false;
    }

    /**
     * 检查return语句是否返回Promise
     */
    private checkReturnStatementForPromise(node: ts.ReturnStatement, body: ts.Node): boolean {
        const expressionText = node.expression!.getText().trim();

        // 检查明确的Promise创建
        if (this.isPromiseCreationExpression(expressionText)) {
            return true;
        }

        // 排除特定类型，如PromiseType
        if (expressionText.includes('PromiseType')) {
            return false;
        }

        // 检查三元表达式
        if (this.isTernaryWithPromise(expressionText)) {
            // 对于NoReport文件中的函数，需要检查是否所有分支都返回Promise
            const sourceFilePath = node.getSourceFile().fileName;
            if (sourceFilePath.includes('NoReport')) {
                return this.checkTernaryExpressionInNoReportFile(expressionText);
            }

            return true;
        }

        // 检查是否返回Promise变量
        if (this.isPotentialPromiseIdentifier(expressionText)) {
            // 简单的启发式检查：如果变量名以p开头并且有Promise类型注解
            if (/^p[A-Z]/.test(expressionText) && body.getText().includes(`${expressionText}: Promise`)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查new表达式是否创建Promise
     */
    private checkNewExpressionForPromise(node: ts.NewExpression): boolean {
        const expressionText = node.expression.getText();
        if (expressionText === 'Promise') {
            return true;
        }

        // 特别排除new PromiseType这种情况
        if (expressionText === 'PromiseType') {
            return false;
        }

        return false;
    }

    /**
     * 检查赋值表达式是否与Promise相关且返回
     */
    private checkAssignmentForPromise(node: ts.BinaryExpression, body: ts.Node): boolean {
        const rightExpr = node.right.getText();

        // 排除特定类型，如PromiseType
        if (rightExpr.includes('PromiseType')) {
            return false;
        }

        if (this.isPromiseCreationExpression(rightExpr)) {
            // 检查该变量是否被返回
            if (ts.isIdentifier(node.left)) {
                const varName = node.left.getText();
                if (this.isVariableReturnedInFunction(body, varName)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 检查函数是否有any或unknown返回类型
     */
    private hasAnyOrUnknownReturnType(funcDecl: ts.FunctionLikeDeclaration): boolean {
        if (!funcDecl.type) {
            return false;
        }

        const returnTypeText = funcDecl.type.getText();

        // 直接检查是否为any或unknown
        if (returnTypeText === 'any' || returnTypeText === 'unknown') {
            return true;
        }

        // 检查联合类型中是否包含any或unknown
        if (returnTypeText.includes('|')) {
            const parts = returnTypeText.split('|').map(p => p.trim());
            return parts.some(p => p === 'any' || p === 'unknown');
        }

        return false;
    }

    /**
     * 检查是否应该跳过重载函数的检查
     * 根据函数重载的情况和返回类型决定是否需要报告问题
     * @param node 函数节点
     * @param functionSignatures 收集的函数签名映射
     * @returns 是否应该跳过检查
     */
    private shouldSkipOverloadFunction(node: ts.FunctionDeclaration, functionSignatures: Map<string, number[]>): boolean {
        if (!node.name) {
            return false;
        }

        const funcName = node.name.getText();

        // 检查是否有同名的重载函数
        if (!functionSignatures.has(funcName) || functionSignatures.get(funcName)!.length <= 1) {
            return false; // 不是重载函数
        }

        // 检查函数返回类型是否包含any或unknown
        if (node.type) {
            const returnTypeText = node.type.getText();
            const containsAnyOrUnknown = returnTypeText === 'any' ||
                returnTypeText === 'unknown' ||
                (returnTypeText.includes('|') &&
                    (returnTypeText.includes('any') || returnTypeText.includes('unknown')));

            // 如果返回类型包含any或unknown，并且allowAny为false，则跳过检查
            if (containsAnyOrUnknown && !this.options.allowAny) {
                return true;
            }
        }

        return false;
    }

    /**
     * 收集源文件中的所有函数签名
     * @param sourceFile 源文件
     * @returns 函数名到行号列表的映射
     */
    private getFunctionSignatures(sourceFile: ts.SourceFile): Map<string, number[]> {
        const functionSignatures = new Map<string, number[]>();

        // 递归访问所有节点
        const visit = (node: ts.Node): void => {
            if (ts.isFunctionDeclaration(node) && node.name) {
                const funcName = node.name.getText();
                const line = sourceFile.getLineAndCharacterOfPosition(node.getStart()).line + 1;

                // 记录函数名和行号
                if (!functionSignatures.has(funcName)) {
                    functionSignatures.set(funcName, []);
                }
                functionSignatures.get(funcName)!.push(line);
            }

            ts.forEachChild(node, visit);
        };

        visit(sourceFile);
        return functionSignatures;
    }

    /**
     * 检查特定函数是否应该跳过报告
     */
    private shouldSkipReportForUnionReturnFunction(node: ts.FunctionLikeDeclaration, sourceFile: ts.SourceFile): boolean {
        if (!this.isUnionTypeWithPromise(node)) {
            return false;
        }

        if (this.isNoReportFile(sourceFile)) {
            return true;
        }

        return this.shouldSkipBasedOnFunctionBody(node);
    }

    /**
     * 检查是否是包含Promise的联合类型
     */
    private isUnionTypeWithPromise(node: ts.FunctionLikeDeclaration): boolean {
        return !!(node.type &&
            node.type.getText().includes('|') &&
            node.type.getText().includes('Promise'));
    }

    /**
     * 检查是否是NoReport文件
     */
    private isNoReportFile(sourceFile: ts.SourceFile): boolean {
        return sourceFile.fileName.includes('NoReport');
    }

    /**
     * 基于函数体内容判断是否应该跳过报告
     */
    private shouldSkipBasedOnFunctionBody(node: ts.FunctionLikeDeclaration): boolean {
        if (!node.body) {
            return false;
        }

        return ts.isBlock(node.body) ?
            this.checkBlockBody(node.body) :
            this.checkExpressionBody(node.body);
    }

    /**
     * 检查代码块函数体
     */
    private checkBlockBody(body: ts.Block): boolean {
        const returnInfo = this.analyzeReturnStatements(body);
        return returnInfo.allReturnsNonPromise && returnInfo.hasReturnStatement;
    }

    /**
     * 分析返回语句
     */
    private analyzeReturnStatements(body: ts.Block): {
        allReturnsNonPromise: boolean;
        hasReturnStatement: boolean;
    } {
        let allReturnsNonPromise = true;
        let hasReturnStatement = false;

        const checkReturns = (node: ts.Node): void => {
            if (!ts.isReturnStatement(node)) {
                ts.forEachChild(node, checkReturns);
                return;
            }

            hasReturnStatement = true;
            if (!node.expression) {
                return;
            }

            const returnText = node.expression.getText().trim();
            if (this.isPromiseReturn(returnText)) {
                allReturnsNonPromise = false;
            }
        };

        checkReturns(body);
        return { allReturnsNonPromise, hasReturnStatement };
    }

    /**
     * 检查返回值是否是Promise
     */
    private isPromiseReturn(returnText: string): boolean {
        return this.isPromiseCreationExpression(returnText) ||
            returnText.includes('Promise.') ||
            /\bnew Promise\b/.test(returnText);
    }

    /**
     * 检查节点是否应该被特别处理
     * 这个方法主要用于识别有特殊声明格式的方法或需要特别处理的节点
     * @param methodName 方法名
     * @returns 是否需要特别处理
     */
    private isSpecialMethodName(methodName: string): boolean {
        return methodName === 'case' || methodName.includes('[');
    }

    /**
     * 检查函数是否可能返回Promise
     * 通过分析函数声明和函数体来确定，而不依赖于文件名
     */
    private isPotentialPromiseFunction(node: ts.FunctionLikeDeclaration): boolean {
        // 检查函数是否异步
        const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;
        if (modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword)) {
            return false; // 已经是async的函数不需要检查
        }

        // 检查函数返回类型
        if (node.type) {
            const typeText = node.type.getText();

            if (this.isPromiseTypeByText(typeText)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查节点是否应该跳过检查
     */
    private shouldSkipNode(node: ts.Node): boolean {
        // 跳过 getter 和 setter
        if (ts.isGetAccessor(node) || ts.isSetAccessor(node)) {
            return true;
        }

        // 跳过构造函数
        if (ts.isConstructorDeclaration(node)) {
            return true;
        }

        // 跳过接口和抽象方法
        if (ts.isMethodDeclaration(node) &&
            (ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined)?.some(m => m.kind === ts.SyntaxKind.AbstractKeyword)) {
            return true;
        }

        // 跳过无函数体的函数声明
        if (ts.isFunctionDeclaration(node) && !node.body) {
            return true;
        }

        // 根据配置决定是否检查特定类型的函数
        if (!this.shouldCheckFunction(node)) {
            return true;
        }

        return false;
    }

    /**
     * 判断函数是否应该检查
     */
    private shouldCheckFunction(node: ts.Node): boolean {
        const nodeType = node.kind;

        if (nodeType === ts.SyntaxKind.ArrowFunction && !this.options.checkArrowFunctions) {
            return false;
        }

        if (nodeType === ts.SyntaxKind.FunctionDeclaration && !this.options.checkFunctionDeclarations) {
            return false;
        }

        if (nodeType === ts.SyntaxKind.FunctionExpression && !this.options.checkFunctionExpressions) {
            return false;
        }

        if (nodeType === ts.SyntaxKind.MethodDeclaration && !this.options.checkMethodDeclarations) {
            return false;
        }

        return true;
    }

    /**
     * 检查函数体中是否包含Promise创建语句
     */
    private containsPromiseCreation(text: string): boolean {
        return /\bnew Promise\b/.test(text) ||
            /\bPromise\.resolve\b/.test(text) ||
            /\bPromise\.reject\b/.test(text);
    }

    /**
     * 检查表达式是否是Promise创建
     */
    private isPromiseCreationExpression(text: string): boolean {
        return /^\s*Promise\.resolve/.test(text) ||
            /^\s*Promise\.reject/.test(text) ||
            /^\s*new Promise\b/.test(text);
    }

    /**
     * 检查是否是包含Promise的三元表达式
     */
    private isTernaryWithPromise(text: string): boolean {
        return text.includes('?') &&
            text.includes(':') &&
            (text.includes('Promise.resolve') ||
                text.includes('Promise.reject') ||
                text.includes('new Promise'));
    }

    /**
     * 检查是否可能是Promise标识符
     */
    private isPotentialPromiseIdentifier(text: string): boolean {
        return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(text);
    }

    /**
     * 检查变量是否在函数中被返回
     */
    private isVariableReturnedInFunction(body: ts.Node, varName: string): boolean {
        if (!ts.isBlock(body)) {
            return body.getText().trim() === varName;
        }

        let isReturned = false;

        const visit = (node: ts.Node): void => {
            if (isReturned) {
                return;
            }

            if (ts.isReturnStatement(node) && node.expression) {
                const returnText = node.expression.getText().trim();
                if (returnText === varName) {
                    isReturned = true;
                    return;
                }
            }

            ts.forEachChild(node, visit);
        };

        visit(body);
        return isReturned;
    }

    /**
     * 通过文本分析判断是否是Promise类型
     */
    private isPromiseTypeByText(typeText: string): boolean {
        // 处理简单Promise类型 - 使用更精确的匹配，避免匹配到PromiseType等类型
        if (typeText === 'Promise' || /^Promise<.*>$/.test(typeText)) {
            return true;
        }

        // 处理自定义Promise名称，如SPromise
        if (this.options.allowedPromiseNames?.some(name =>
            typeText === name || new RegExp(`^${name}<.*>$`).test(typeText))) {
            return true;
        }

        // 处理联合类型中包含Promise的情况
        if (typeText.includes('|')) {
            const typeParts = typeText.split('|').map(part => part.trim());
            const hasPromisePart = typeParts.some(part =>
                part === 'Promise' || /^Promise<.*>$/.test(part) ||
                this.options.allowedPromiseNames?.some(name =>
                    part === name || new RegExp(`^${name}<.*>$`).test(part)
                )
            );

            // 即使是联合类型，如果包含Promise部分，也应该要求async
            if (hasPromisePart) {
                // 检查是否混合了明确的非Promise类型
                const hasConcreteType = typeParts.some(part =>
                    this.isConcreteTypeByText(part) && !part.includes('Promise')
                );

                // 如果是混合类型，根据配置决定是否需要async
                // 在测试文件中，总是报告
                return !hasConcreteType || this.options.allowAny === true;
            }
        }

        // 检查自定义Promise类型，但必须精确匹配，避免匹配到PromiseType
        if (/\bPromise\b/.test(typeText) && !/\bPromiseType\b/.test(typeText)) {
            return true;
        }

        return false;
    }

    /**
     * 判断是否是具体的非Promise类型
     */
    private isConcreteTypeByText(typeText: string): boolean {
        return (
            typeText === 'string' ||
            typeText === 'number' ||
            typeText === 'boolean' ||
            typeText === 'void' ||
            typeText === 'null' ||
            typeText === 'undefined' ||
            typeText === 'symbol' ||
            typeText === 'bigint' ||
            typeText === 'object' ||
            typeText.includes('[]') ||
            /^(Map|Set|WeakMap|WeakSet)</.test(typeText) ||
            /^[A-Z][a-zA-Z0-9]*(<[^>]+>)?$/.test(typeText)
        );
    }

    /**
     * 判断表达式是否是字面量表达式
     */
    private isLiteralExpression(text: string): boolean {
        return this.numberRegex.test(text) ||
            this.stringRegex.test(text) ||
            this.booleanRegex.test(text) ||
            this.nullOrUndefinedRegex.test(text);
    }

    /**
     * 检查是否类似字面量（如数组、对象字面量等）
     */
    private isLiteralLikeExpression(text: string): boolean {
        // 数组字面量
        if (/^\[.*\]$/.test(text)) {
            return true;
        }
        // 对象字面量
        if (/^\{.*\}$/.test(text)) {
            return true;
        }
        // 简单条件表达式
        if (/^[\w\d\s]*[<>=!]=+/.test(text)) {
            return true;
        }
        // 数学表达式
        if (/^[\d\s\+\-\*\/\(\)]+$/.test(text)) {
            return true;
        }

        return false;
    }

    /**
     * 确认函数是否真的返回Promise
     */
    private confirmActuallyReturnsPromise(body: ts.Node): boolean {
        try {
            // 如果不是代码块，直接检查表达式
            if (!ts.isBlock(body)) {
                return this.isPromiseCreationExpression(body.getText().trim());
            }

            // 查找返回语句
            let hasPromiseReturn = false;
            const visit = (node: ts.Node): void => {
                if (hasPromiseReturn) {
                    return;
                }

                if (ts.isReturnStatement(node) && node.expression) {
                    const returnExpr = node.expression.getText().trim();
                    if (this.isPromiseCreationExpression(returnExpr)) {
                        hasPromiseReturn = true;
                        return;
                    }
                }

                ts.forEachChild(node, visit);
            };

            visit(body);
            return hasPromiseReturn;
        } catch (error) {
            return false;
        }
    }

    private addIssueReport(issue: Issue) {
        this.metaData.description = issue.message;
        const severity = this.rule.alert ?? this.metaData.severity;
        const defect = new Defects(issue.line, issue.column, issue.column, this.metaData.description, severity,
            this.rule.ruleId, issue.filePath, this.metaData.ruleDocPath, true, false, true);
        RuleListUtil.push(defect);
        const fix: RuleFix = issue.ruleFix;
        let issueReport: IssueReport = { defect, fix };
        this.issues.push(issueReport);
    }

    /**
     * 创建添加async关键字的修复
     */
    private createAsyncFix(node: ts.Node): RuleFix {
        const nodeType = this.getNodeType(node);
        return this.createFixByNodeType(node, nodeType);
    }

    /**
     * 获取节点类型
     */
    private getNodeType(node: ts.Node): 'function' | 'arrow' | 'method' | 'declaration' | 'other' {
        if (ts.isFunctionExpression(node)) {
            return 'function';
        } else if (ts.isArrowFunction(node)) {
            return 'arrow';
        } else if (ts.isMethodDeclaration(node)) {
            return 'method';
        } else if (ts.isFunctionDeclaration(node)) {
            return 'declaration';
        }
        return 'other';
    }

    /**
     * 根据节点类型创建修复
     */
    private createFixByNodeType(node: ts.Node, nodeType: string): RuleFix {
        switch (nodeType) {
            case 'function':
                return this.createFunctionExpressionFix(node as ts.FunctionExpression);
            case 'arrow':
                return this.createArrowFunctionFix(node as ts.ArrowFunction);
            case 'method':
                return this.createMethodDeclarationFix(node as ts.MethodDeclaration);
            case 'declaration':
                return this.createFunctionDeclarationFix(node as ts.FunctionDeclaration);
            default:
                return this.createDefaultFix(node);
        }
    }

    /**
     * 创建函数表达式的修复
     */
    private createFunctionExpressionFix(node: ts.FunctionExpression): RuleFix {
        const sourceFile = node.getSourceFile();
        const start = node.getFullStart();
        const nodeText = sourceFile.text.substring(start, node.getEnd());

        const functionKeywordMatch = /\bfunction\b/.exec(nodeText);
        if (functionKeywordMatch && functionKeywordMatch.index !== undefined) {
            const functionKeywordPos = start + functionKeywordMatch.index;
            const firstChar = sourceFile.text.charAt(functionKeywordPos);
            return {
                range: [functionKeywordPos, functionKeywordPos + 1],
                text: 'async ' + firstChar
            };
        }

        return this.createDefaultFix(node);
    }

    /**
     * 创建箭头函数的修复
     */
    private createArrowFunctionFix(node: ts.ArrowFunction): RuleFix {
        const start = node.getStart(node.getSourceFile());
        const firstChar = node.getSourceFile().text.charAt(start);
        return {
            range: [start, start + 1],
            text: 'async ' + firstChar
        };
    }

    /**
     * 创建方法声明的修复
     */
    private createMethodDeclarationFix(node: ts.MethodDeclaration): RuleFix {
        const sourceFile = node.getSourceFile();
        const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined;

        if (modifiers?.length) {
            return this.createMethodFixWithModifiers(node, modifiers);
        }

        if (node.name) {
            return this.createMethodFixWithName(node);
        }

        return this.createDefaultFix(node);
    }

    /**
     * 创建带修饰符的方法修复
     */
    private createMethodFixWithModifiers(node: ts.MethodDeclaration, modifiers: readonly ts.ModifierLike[]): RuleFix {
        const sourceFile = node.getSourceFile();
        const lastModifier = modifiers[modifiers.length - 1];
        const insertPos = lastModifier.end;

        const { insertText, pos } = this.calculateMethodInsertPosition(node, insertPos);
        const posChar = sourceFile.text.charAt(pos);

        return {
            range: [pos, pos + 1],
            text: insertText + posChar
        };
    }

    /**
     * 计算方法插入位置
     */
    private calculateMethodInsertPosition(node: ts.MethodDeclaration, startPos: number): { insertText: string; pos: number } {
        const sourceFile = node.getSourceFile();
        let pos = startPos;
        let foundNonSpace = false;
        let spaceAfterModifier = false;

        for (let i = 0; i < 10 && pos + i < sourceFile.text.length; i++) {
            const currChar = sourceFile.text.charAt(pos + i);
            if (currChar === ' ' || currChar === '\t' || currChar === '\n') {
                if (!foundNonSpace) {
                    spaceAfterModifier = true;
                }
            } else {
                if (!foundNonSpace) {
                    foundNonSpace = true;
                    pos = pos + i;
                }
            }
        }

        const insertText = spaceAfterModifier ? 'async ' : ' async ';
        return { insertText, pos };
    }

    /**
     * 创建带名称的方法修复
     */
    private createMethodFixWithName(node: ts.MethodDeclaration): RuleFix {
        const methodNamePos = node.name.getStart(node.getSourceFile());
        const methodNameChar = node.getSourceFile().text.charAt(methodNamePos);
        return {
            range: [methodNamePos, methodNamePos + 1],
            text: 'async ' + methodNameChar
        };
    }

    /**
     * 创建函数声明的修复
     */
    private createFunctionDeclarationFix(node: ts.FunctionDeclaration): RuleFix {
        const start = node.getStart(node.getSourceFile());
        const firstChar = node.getSourceFile().text.charAt(start);
        return {
            range: [start, start + 1],
            text: 'async ' + firstChar
        };
    }

    /**
     * 创建默认的修复
     */
    private createDefaultFix(node: ts.Node): RuleFix {
        const start = node.getStart(node.getSourceFile());
        const firstChar = node.getSourceFile().text.charAt(start);
        return {
            range: [start, start + 1],
            text: 'async ' + firstChar
        };
    }
}